var sess = sessionStorage.getItem("session");
var groupid = 0;
var gridArea = [];
var dataArea = '';
var userstate = '';
if (!sess) {
	window.top.location = "../../login.html";
}
$(document).ready(function() {
	var arr = [
		['1', '激活'],
		['2', '禁用']
	];
	$("#state").combobox({
		data: arr,
		valueField: 0,
		textField: 1,
		value: "1",
		editable: false,
	});

	$('#departmentId').combobox({
		url: IP + "GetDepartmentInfo?callback=?",
		valueField: 'id',
		textField: 'text',
		editable: false,
		onLoadSuccess: function() {  
					var val = $(this).combobox("getData");
					for (var item in val[0]) {
						if (item == "id") {
							$(this).combobox("select", val[0][item]);
						}
					}
				 
				}
	});
    
	$('#tt').tree({
		url: IP + "GetDepartmentInfo?callback=?",
		loadFilter: function(rows) {
			return convert(rows);
		},

		onClick: function(node) {
			groupid = node.id;
			if (node.id == 1) {
				$('#jqGrid').jqGrid('setGridParam', {
					url: IP + "GetOperateInfoList?callback=?&groupId=0&session=" + sess,
					type: 'Get',
					datatype: "jsonp",
				}).trigger('reloadGrid');
			} else {
				$('#jqGrid').jqGrid('setGridParam', {
					url: IP + "GetOperateInfoList?callback=?&groupId=" + groupid + "&session=" + sess,
					type: 'Get',
					datatype: "jsonp",
				}).trigger('reloadGrid');
			}
			$('#departmentId').combobox('setValue', groupid);
		}
	});
     AddRow();
	$.extend($.fn.validatebox.defaults.rules, {
		mobile: { // 验证手机号码
			validator: function(value) {
				return /^(13|15|18)\d{9}$/i.test(value);
			},
			message: '手机号码格式不正确'
		},
		phone: {
			validator: function(value) {
				var rex2 = /^((0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/;
				return rex2.test(value);
			},
			message: '电话号码格式不正确'
		}
	});
	$.getJSON(IP + "GetDepartmentInfo?callback=?", function(data) {
		gridArea = data;
		//	console.log(gridArea);
		for (var i = 0; i < gridArea.length; i++) {
			dataArea = dataArea + gridArea[i].id + ":" + gridArea[i].text + ";";
		}
		userstate = '1:激活;2:禁用';
		//		console.log(dataArea);
		BindGrid();
	});
	var template1 = {
		"groupOp": "AND",
		"rules": [{
			"field": "empno",
			"op": "eq",
			"data": "W"
		}, {
			"field": "loginName",
			"op": "le",
			"data": "15"
		}]
	};
	// activate the build in search with multiple option
	$('#jqGrid').navGrid("#jqGridPager", {
			search: true, // show search button on the toolbar
			add: false,
			edit: false,
			del: false,
			refresh: true
		}, {}, // edit options
		{}, // add options
		{}, // delete options
		{
			multipleSearch: true,
			multipleGroup: true,
			showQuery: true,
			// set the names of the template
			tmplNames: ["模板一"],
			// set the template contents
			tmplFilters: [template1]
		} // search options - define multiple search
	);
	
});



function BindGrid() {
	$("#jqGrid").jqGrid({
		url: IP + "GetOperateInfoList?callback=?&groupId=" + groupid + "&session=" + sess,
		mtype: "Get",
		datatype: "jsonp",
		colModel: [{
			label: 'id',
			name: 'id',
			//			width: 70
			hidden: true
		}, {
			label: '工号',
			name: 'empno',
			width: 70
		}, {
			label: '所在县市',
			name: 'departmentId',
			width: 80,
			formatter: "select",
			editoptions: {
				value: dataArea
			},
		}, {
			label: '注册姓名',
			name: 'loginName',
			width: 100,
			hidden: true,
		}, {
			label: '真实姓名',
			name: 'realName',
			width: 80
		}, {
			label: '邮箱地址',
			name: 'email',
			width: 130
		}, {
			label: '手机号',
			name: 'phoneNumber',
			width: 100
		}, {
			label: '联系电话',
			name: 'telNumber',
			width: 100
		}, {
			label: '联系地址',
			name: 'address',
			width: 100
		}, {
			label: '当前状态',
			name: 'state',
			width: 50,
			formatter: "select",
			editoptions: {
				value: userstate
			},
		}, {
			label: '注册密码',
			name: 'loginPasswd',
			width: 100,
			hidden: true,
		}, {
			label: '备注',
			name: 'memo',
			width: 100,

		}],
		viewrecords: true,
		rowNum: 11,
		loadonce: true,
		page: 1,
		autowidth: true,
		rownumbers:true,
		loadtext: '正在加载数据',
		pager: "#jqGridPager",
		onSelectRow: function(rowid) {
			$("#empno").textbox("disable");
		},
		loadComplete:function(){
			var h =$("body").height();
			 
			$("#jqGrid").jqGrid("setGridHeight",h-240);
		}
	});
}
document.onkeydown = function() {
	if (event.ctrlKey && event.keyCode == 13) {
		SaveRow();
	}
}

 

function AddRow() {
	$("#empno").textbox("enable");
	$("#state").combobox("setValue", "1");
	$('#ff').form('load', {
		id: 0,
		empno: '',
		loginName: '',
		loginPasswd: '',
		realName: '',
		email: '',
		phoneNumber: '',
		telNumber: '',
		memo: '',
	});
	$("#tt").tree("reload");
	$("#jqGrid").trigger("reloadGrid");
}

function EditRow() {
	$("#empno").textbox("enable");
	var grid = $("#jqGrid");
	var rowKey = grid.jqGrid('getGridParam', "selrow");
	var state = $("#jqGrid").getCell(rowKey, "state");
	$("#state").combobox("setValue", state);
	if (rowKey) {
		$('#ff').form('load', {
			id: $("#jqGrid").getCell(rowKey, "id"),
			empno: $("#jqGrid").getCell(rowKey, "empno"),
			loginName: $("#jqGrid").getCell(rowKey, "loginName"),
			loginPasswd: $("#jqGrid").getCell(rowKey, "loginPasswd"),
			realName: $("#jqGrid").getCell(rowKey, "realName"),
			email: $("#jqGrid").getCell(rowKey, "email"),
			phoneNumber: $("#jqGrid").getCell(rowKey, "phoneNumber"),
			departmentId: $("#jqGrid").getCell(rowKey, "departmentId"),
			telNumber: $("#jqGrid").getCell(rowKey, "telNumber"),
			address: $("#jqGrid").getCell(rowKey, "address"),
			memo: $("#jqGrid").getCell(rowKey, "memo"),
		});
	} else {
		$.messager.alert('提醒', "没有选中行", 'info');
	}
	console.log($("#jqGrid").getCell(rowKey, "id"));
}

function DeleteRow() {
	var grid = $("#jqGrid");
	var rowKey = grid.jqGrid('getGridParam', "selrow");
	if (rowKey) {
		$.messager.confirm('删除提醒', '你确认要删除用户信息---' + $("#jqGrid").getCell(rowKey, "loginName") + '?', function(r) {
			if (r) {

				$.ajax({
					type: "post", // 与可以 "get"
					url: IP + "DeleteOperateInfo?",
					data: {
						id: rowKey,
					},
					dataType: "jsonp",
					jsonp: "callback",
					jsonpCallback: "resultHandler",
					success: function(json) {
						if (json.result == 200) {
							$("#jqGrid").delRowData(rowKey);
							insertopertlog('系统管理', '用户管理', '删除', $("#jqGrid").getCell(rowKey, "loginName"), '');
							$.messager.show({
								title: '提醒',
								msg: '删除成功',
								timeout: 1300,
								showType: 'slide',
								style: {
									right: '',
									bottom: ''
								}
							});
						} else {
							$.messager.alert('删除失败', json.message, 'error');
						}
					}
				});
			}
		});
	} else {
		$.messager.alert('提醒', "没有选中行", 'info');
	}
}

function SaveRow() {
	var grid = $("#jqGrid");
	var rowKey = grid.jqGrid('getGridParam', "selrow");
	var oldvalue = $("#jqGrid").getCell(rowKey, "loginName");
	var state = $("#state").combobox("getValue");
	if ($('#ff').form('enableValidation').form('validate')) {
		$.ajax({
			type: "post", // 与可以 "get"
			url: IP + "UpdateOperateInfo?callback=?&session" + session,
			data: {
				id: $("#id").val(),
				loginName: $("#loginName").val(),
				loginPasswd: $("#loginPasswd").val(),
				empno: $("#empno").val(),
				realName: $("#realName").val(),
				email: $("#email").val(),
				phoneNumber: $("#phoneNumber").val(),
				departmentId: $('#departmentId').textbox('getValue'),
				telNumber: $("#telNumber").val(),
				address: $("#address").val(),
				state: state,
				memo: $("#memo").val(),
			},
			dataType: "jsonp",
			jsonp: "callback",
			jsonpCallback: "resultHandler",
			success: function(json) {
				if (json.result = 200) {
					if ($('#id').val() == 0) {
						$("#jqGrid").addRowData(json.id, {
							id: json.id,
							loginName: $("#loginName").val(),
							loginPasswd: $("#loginPasswd").val(),
							empno: $("#empno").val(),
							realName: $("#realName").val(),
							email: $("#email").val(),
							phoneNumber: $("#phoneNumber").val(),
							departmentId: $('#departmentId').textbox('getValue'),
							telNumber: $("#telNumber").val(),
							address: $("#address").val(),
							state: state,
							memo: $("#memo").val(),
						}, '');
						insertopertlog('系统管理', '用户管理', '新增', '', $("#loginName").val());
						$.messager.show({
							title: '提醒',
							msg: '用户增加成功',
							timeout: 1300,
							showType: 'slide',
							style: {
								right: '',
								bottom: ''
							}
						});
					} else {
						$("#jqGrid").setRowData($('#id').val(), {
							id: $("#id").val(),
							loginName: $("#loginName").val(),
							loginPasswd: $("#loginPasswd").val(),
							empno: $("#empno").val(),
							realName: $("#realName").val(),
							email: $("#email").val(),
							phoneNumber: $("#phoneNumber").val(),
							departmentId: $('#departmentId').textbox('getValue'),
							telNumber: $("#telNumber").val(),
							address: $("#address").val(),
							state: state,
							memo: $("#memo").val(),
						}, '');
						insertopertlog('系统管理', '用户管理', '修改', oldvalue, $("#loginName").val());
						$.messager.show({
							title: '提醒',
							msg: '用户修改成功',
							timeout: 1300,
							showType: 'slide',
							style: {
								right: '',
								bottom: ''
							}
						});
					}
				} else {
					$.messager.alert('保存失败', json.message, 'error');
				}
				//保存成功后，重置控件，以免用户重复提交
				AddRow();
			}
		});
	}
}

function convert(json) {

	var json1 = {
		"pid": 0,
		"id": 1,
		"text": "县市",
		"state": true,
		"checked": false
	};
	json1.children = json;
	var json2 = [];
	json2.push(json1);

	return json2;
}